package com.pingan.haofang.searchcloud.api.query.parser.dbobject.sqlnode.aggregate;

import java.util.Arrays;

import org.apache.commons.collections.CollectionUtils;

import com.pingan.haofang.searchcloud.api.query.parser.dbobject.OrderBySupport;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.SelectItemSupport;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.SqlNodeType;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.exception.FunctionExecuteException;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.sqlnode.ColumnNode;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.sqlnode.function.Function;

public abstract class AggregateFunction extends Function implements OrderBySupport, SelectItemSupport {

    protected boolean asc = true;
    protected Class<?> javaType;

    public int getType() {
        return SqlNodeType.AGGREGATE_FUNCTION;
    }

    public boolean isAsc() {
        return asc;
    }

    public void setAsc(boolean asc) {
        this.asc = asc;
    }

    public Class<?> getJavaType() {
        return javaType;
    }

    public void setJavaType(Class<?> javaType) {
        this.javaType = javaType;
    }

    public ColumnNode getColumn() {
        return CollectionUtils.isNotEmpty(params) ? (ColumnNode) params.get(0) : null;
    }

    protected void assertParamCount(Object[] params, int expect) {
        if (params == null) {
            throw new FunctionExecuteException("params count is illegal, expect: " + expect + ", actual: 0");
        }
        if (params.length != expect) {
            throw new FunctionExecuteException(
                    "params count is illegal, expect: " + expect + ", actual:" + params.length);
        }
    }

    protected void assertParamType(Object[] params, Class<?>...expects) {
        for (Object param : params) {
            boolean flag = false;
            for (Class<?> expect : expects) {
                if (expect.isAssignableFrom(param.getClass())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                throw new FunctionExecuteException("param's type is illegal, expect: " + Arrays.toString(expects)
                        + ", actual:" + param.getClass().getName());
            }
        }
    }
}
